const request = require("../utils/request");
const api = request.default;
const sm2 = require("sm-crypto").sm2;

const keypair = sm2.generateKeyPairHex();
const publicKey = keypair.publicKey;
const privateKey = keypair.privateKey;

let data = "";
const timeout = 1000 * 60 * 5;
/**
 * TODO: 得考虑增加过滤字典项的方法
 */
module.exports = {
  async getList(name) {
    const list = JSON.parse(window.sessionStorage.getItem(name));
    if (list == null) {
      let data = {}
      if (name=='行政区划'){
        data = await api.post(`/api/dict/organ/list`);
      }else{
        data = await api.post(`/api/dict/list`, { name });
      }
      const { success, result, code, msg } = data;
      if (success) {
        if (result.hasOwnProperty("rows")) {
          window.sessionStorage.setItem(
            name,
            JSON.stringify({ rows: result.rows, time: new Date().getTime() })
          );
          return result.rows;
        }
      } else {
        console.error(`错误代码:${code},${msg}`);
        return [];
      }
    } else {
      window.sessionStorage.setItem(
        name,
        JSON.stringify({ rows: list.rows, time: new Date().getTime() })
      );
      return list.rows;
    }
  },
  async getTree(name) {
    const tree = JSON.parse(window.sessionStorage.getItem(name + "-tree"));
    if (tree == null) {
      let data = {}
      if (name=='行政区划'){
        data = await api.post(`/api/dict/organ`);
      }else{
        data = await api.post(`/api/dict/tree`, { name });
      }
      const { success, result, code, msg } = data;
      if (success) {
        window.sessionStorage.setItem(
          name + "-tree",
          JSON.stringify({ tree: result, time: new Date().getTime() })
        );
        return result;
      } else {
        console.error(`错误代码:${code},${msg}`);
        return [];
      }
    } else {
      return tree.tree;
    }
  },
  async getTitle(name, code) {
    const list = getList(name);
    return list.find((item) => item.code == code);
  },
  async getCode(name, title) {
    const list = getList(name);
    return list.find((item) => item.title == title);
  },
  setUserList() {
    //TODO: 加载所有用户信息到本地，并加密
    return new Promise((resolve, reject) => {
      api.findAll('meta','staff').then((data) => {
        const { result, success, msg} = data;
        if (success) {
          window.localStorage.setItem(
            "user-list",
            sm2.doEncrypt(JSON.stringify(result.rows), publicKey, 1)
          );
          resolve()
        } else {
            reject(new Error("error"))
        }
      });
    });
  },
  getUserList() {
    return JSON.parse(
      sm2.doDecrypt(window.localStorage.getItem("user-list"), privateKey, 1)
    );
  },
  getUser(id) {
    const userList = JSON.parse(
      sm2.doDecrypt(window.localStorage.getItem("user-list"), privateKey, 1)
    );
    return userList.find((user) => user.id == id);
  },
  autoClear() {
    window.setInterval(function() {
      for (let i = 0; i < window.sessionStorage.length; i++) {
        const obj = JSON.parse(
          window.sessionStorage.getItem(window.sessionStorage.key(i))
        );
        if (obj != null) {
          if (obj.hasOwnProperty("time")) {
            if (new Date().getTime() - obj.time) {
              window.sessionStorage.removeItem(window.sessionStorage.key(i));
            }
          }
        }
      }
    }, timeout);
  },
};
